#include "adapt.h"
#include "eth.h"
#include "pci.h"

static netAdapter_t *adapters[250];
static int adapterCount = 0;

int netAddAdapter(int type, void *data)
{
	netAdapter_t *newAdapter;
	netAdapter_t **new;

	newAdapter = (netAdapter_t *)kmalloc(sizeof(netAdapter_t));
	if(!newAdapter)
	{
		PANIC("no now adapter!");
		return 0;
	}
	newAdapter->type = type;
	newAdapter->ipaddr = 0;
	newAdapter->netmask = 0;
	newAdapter->broadcast = 0;
	newAdapter->errors = 0;
	newAdapter->dropped = 0;
	newAdapter->received = 0;
	newAdapter->up = 0;
	newAdapter->mtu = 1500;

	switch(type)
	{
		case NET_TYPE_ETHER:
		{
			
			struct ethernet_t *eth = (struct ethernet_t *)data;
			newAdapter->hwaddr = 
				(struct netHwAddr_t *)kmalloc(sizeof(struct netHwAddr_t));
			if(!newAdapter->hwaddr)
			{
				kfree((char*)newAdapter);
				return 0;
			}
			newAdapter->hwaddr->type = NET_TYPE_ETHER;
			newAdapter->hwaddr->dataSize = 6;
			
			u8int *dest = newAdapter->hwaddr->u.ethernet;
			u8int *src = eth->macAddr;
			u32int *len = newAdapter->hwaddr->dataSize;
			
			
			memcpy(dest, src,len);
			eth->adapter = newAdapter;
			break;
		}
		default:
		{
			printf("Adapter unknown type.....\n");
			kfree((char*)newAdapter);
			return 0;
		}
		
	}

/*	if(!adapterCount)
	{
		adapters = (netAdapter_t **)kmalloc(sizeof(netAdapter_t *));
		if(!adapters)
		{
			kfree(newAdapter->hwaddr);
			kfree(newAdapter);
			return 0;
		}
	}
	else
	{
		new = (netAdapter_t **)krealloc(adapters, sizeof(netAdapter_t *) * (
										adapterCount + 1));

		if(!new)
		{
			kfree(newAdapter->hwaddr);
			kfree(newAdapter);
			return 0;
		}
		adapters = new;
	}*/
	adapters[adapterCount++] = newAdapter;
	return 1;
}

// net interface config
int netIfconfig(char *device, ifconfig_t *conf, int up)
{
	netAdapter_t *nic;
	
	//TODO
	nic = ethGetAdapterByName(device);
	if(!nic)
	{
		printf( "Invalid NIC\n" );
		return -1;
	}else
		printf(" (NIC IS UP) ");

	if(!conf)
	{
		nic->up = up;
		return 0;
	}
	
	if(conf->ipaddr)
		nic->ipaddr = conf->ipaddr;
	
	if(conf->broadcast)
		nic->broadcast = conf->broadcast;
	
	if(conf->netmask)
		nic->netmask = conf->netmask;

	if(conf->mtu)
		nic->mtu = conf->mtu;
		
	if(conf->network)
		nic->network = conf->network;
		
	if(conf->gateway)
		nic->gateway = conf->gateway;
		
	if(conf->dns)
		nic->dns = conf->dns;
	
	nic->dropped = 0;
	nic->errors = 0;

	nic->up = up;
	
	return 0;
}
